package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.PageParam;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper mapper;

    @Override
    public int findCountByCategoryId(long categoryId) {


        //创建查询对象
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);

        //执行查询
        return mapper.selectCount(qw);
    }

    /**
     * wurenfeng
     */
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品添加
     * @param dishDto
     * @return
     */
    @Override
    public int add(DishDto dishDto) {
        int row1 = mapper.insert(dishDto);
        //添加口味数据
        List<DishFlavor> list = dishDto.getFlavors();
        int row2 = 0;
        if (list != null && list.size()>0){
            for (DishFlavor dishFlavor : list) {
                dishFlavor.setDishId(dishDto.getId());
                row2+=dishFlavorService.add(dishFlavor);
            }
            return row1>0&&row2==list.size()?1:0;
        }
        return row1;
    }

    /**
     * 分页查询菜品管理
     * @param pageParam
     * @return
     */
    @Override
    public IPage findPage(PageParam pageParam) {
        IPage<Dish> page = new Page<>(pageParam.getPage(),pageParam.getPageSize());
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(pageParam.getName() != null , Dish::getName,pageParam.getName());
        mapper.selectPage(page,lqw);

        //自己创建Ipage<dishdto>
        IPage<DishDto> dishDtoIPage = new Page<>();
        //将page中的total，records复制到dishDtoIpage中
        dishDtoIPage.setTotal(page.getTotal());
        //设置records数据
        //用流的方式遍历原先从数据库里面查询得到的10条记录
        List<DishDto> list = page.getRecords().stream().map(dish->{
            //创建dishDto
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);

            dishDto.setCategoryName(categoryService.findById(dish.getCategoryId()).getName());

            dishDto.setFlavors(dishFlavorService.findByDishId(dish.getId()));
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoIPage.setRecords(list);
        return dishDtoIPage;
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @Override
    public int update(DishDto dishDto) {
        int rows = mapper.updateById(dishDto);
        //删除口味数据
        dishFlavorService.delete(dishDto.getId());

        //执行口味数据的添加
        int rows2 = 0;
        List<DishFlavor> dishFlavors = dishDto.getFlavors();

        if (dishFlavors != null && dishFlavors.size()>0){
            for (DishFlavor dishFlavor : dishFlavors) {
                dishFlavor.setDishId(dishDto.getId());
                rows2 += dishFlavorService.add(dishFlavor);
            }
            return rows>0 && rows2 == dishFlavors.size() ? 1:0;
        }
        return rows;
    }

    /**
     * 单个删除和批量删除菜品
     */
    @Override
    public int delete(List<Long> ids) {
        //先查询是否有起售状态，有就抛异常
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getStatus,1).in(Dish::getId,ids);
        int count = mapper.selectCount(lqw);
        if (count>0){
            throw new CustomException("启售状态，禁止删除");
        }else {
            int rows = mapper.deleteBatchIds(ids);
            for (Long id : ids) {
                 dishFlavorService.deleteByDishId(id);
            }
            return rows;
        }
//        try {
//            throw new CustomException("套餐包含起售状态，禁止删除");
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    /**
     * 批量起售停售及单个起售停售
     */
    @Override
    public int updateStatus(List<Long> ids,Integer status) {
        //update dish set status = ? where id = ids
        int rows=0;
        for (Long id : ids) {
            LambdaUpdateWrapper<Dish> wrapper =new LambdaUpdateWrapper();
            wrapper.set(Dish::getStatus, status);
            wrapper.eq(Dish::getId,id);
            int update = mapper.update(null, wrapper);
            rows+=update;
        }
        return (rows==ids.size()?1:0);
    }

    @Override
    public List<Dish> dishList(Long categoryId,Integer status) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(categoryId!=null,Dish::getCategoryId, categoryId);
        qw.eq(status!=null,Dish::getStatus, status);
        return mapper.selectList(qw);
    }

    //查询分类id
    @Override
    public Long findCategoryId(Long id) {
        LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<>();
        qw.eq(Dish::getId,id);
        return mapper.selectOne(qw).getCategoryId();
    }
}
